package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/middlewar/middleware"
)

func main() {
	// 设置Gin模式
	gin.SetMode(gin.ReleaseMode)

	r := gin.New() // 使用gin.New()而不是gin.Default()，这样我们可以完全控制中间件

	// 全局中间件链 - 按照执行顺序配置
	r.Use(
		middleware.Recovery(),       // 1. 异常恢复（最先执行，确保能捕获所有panic）
		middleware.RequestLogger(),  // 2. 请求日志（记录所有请求）
		middleware.CORSMiddleware(), // 3. 跨域处理
	)

	// 公开路由（不需要认证）
	public := r.Group("/api/public")
	{
		// 健康检查  http://localhost:8080/api/public/health
		public.GET("/health", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"status":    "ok",
				"timestamp": c.GetString("requestID"),
			})
		})

		// 登录接口 http://localhost:8080/api/public/login
		public.POST("/login", func(c *gin.Context) {
			var loginReq struct {
				Username string `json:"username" binding:"required"`
				Password string `json:"password" binding:"required"`
			}

			if err := c.ShouldBindJSON(&loginReq); err != nil {
				c.JSON(http.StatusBadRequest, gin.H{
					"error":     "invalid request",
					"details":   err.Error(),
					"requestID": c.GetString("requestID"),
				})
				return
			}

			// 简单的用户验证逻辑（实际项目中应该查询数据库）
			if loginReq.Username == "admin" && loginReq.Password == "admin123" {
				token, err := middleware.GenerateToken("admin", []string{"admin", "user"})
				if err != nil {
					c.JSON(http.StatusInternalServerError, gin.H{
						"error":     "failed to generate token",
						"requestID": c.GetString("requestID"),
					})
					return
				}

				c.JSON(http.StatusOK, gin.H{
					"message":   "login successful",
					"token":     token,
					"userID":    "admin",
					"roles":     []string{"admin", "user"},
					"requestID": c.GetString("requestID"),
				})
			} else if loginReq.Username == "user" && loginReq.Password == "user123" {
				token, err := middleware.GenerateToken("user", []string{"user"})
				if err != nil {
					c.JSON(http.StatusInternalServerError, gin.H{
						"error":     "failed to generate token",
						"requestID": c.GetString("requestID"),
					})
					return
				}

				c.JSON(http.StatusOK, gin.H{
					"message":   "login successful",
					"token":     token,
					"userID":    "user",
					"roles":     []string{"user"},
					"requestID": c.GetString("requestID"),
				})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{
					"error":     "invalid credentials",
					"requestID": c.GetString("requestID"),
				})
			}
		})

		// 测试panic恢复
		public.GET("/panic", func(c *gin.Context) {
			panic("这是一个测试panic")
		})
	}

	// 需要JWT认证的路由
	authenticated := r.Group("/api/auth")
	authenticated.Use(middleware.JWTAuth()) // 添加JWT认证中间件
	{

		// 用户信息 http://localhost:8080/api/auth/profile   header里面添加
		authenticated.GET("/profile", func(c *gin.Context) {
			userID := c.GetString("userID")
			roles, _ := c.Get("roles")

			c.JSON(http.StatusOK, gin.H{
				"userID":    userID,
				"roles":     roles,
				"message":   "profile data",
				"requestID": c.GetString("requestID"),
			})
		})

		// 所有认证用户都可以访问的资源
		authenticated.GET("/dashboard", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message":   "welcome to dashboard",
				"userID":    c.GetString("userID"),
				"requestID": c.GetString("requestID"),
			})
		})
	}

	// 需要管理员权限的路由
	admin := r.Group("/api/admin")
	admin.Use(
		middleware.JWTAuth(),            // JWT认证
		middleware.RequireRole("admin"), // 需要admin角色
	)
	{
		admin.GET("/users", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message":   "user list (admin only)",
				"users":     []string{"user1", "user2", "admin"},
				"requestID": c.GetString("requestID"),
			})
		})

		admin.POST("/system/config", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message":   "system config updated (admin only)",
				"requestID": c.GetString("requestID"),
			})
		})
	}

	// 需要多种角色之一的路由
	moderator := r.Group("/api/moderator")
	moderator.Use(
		middleware.JWTAuth(),
		middleware.RequireRole("admin", "moderator"), // 需要admin或moderator角色
	)
	{
		moderator.GET("/reports", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{
				"message":   "reports data (admin or moderator)",
				"requestID": c.GetString("requestID"),
			})
		})
	}

	// 启动服务器
	println("🚀 服务器启动在端口 :8080")
	println("📖 API文档:")
	println("  公开接口:")
	println("    GET  /api/public/health   - 健康检查")
	println("    POST /api/public/login    - 用户登录")
	println("    GET  /api/public/panic    - 测试panic恢复")
	println("")
	println("  认证接口 (需要JWT token):")
	println("    GET  /api/auth/profile    - 获取用户信息")
	println("    GET  /api/auth/dashboard  - 用户仪表板")
	println("")
	println("  管理员接口 (需要admin角色):")
	println("    GET  /api/admin/users     - 获取用户列表")
	println("    POST /api/admin/system/config - 系统配置")
	println("")
	println("  版主接口 (需要admin或moderator角色):")
	println("    GET  /api/moderator/reports - 获取报告")
	println("")
	println("💡 测试账户:")
	println("  管理员: admin / admin123 (角色: admin, user)")
	println("  普通用户: user / user123 (角色: user)")

	if err := r.Run(":8080"); err != nil {
		panic("服务器启动失败: " + err.Error())
	}
}
